<script lang="ts">
    import { Power, STM32_Power, Stm32_chart, Motor_1_chart, Motor_2_chart, V_I_chart, shebeiState, jiankongState, 
        motionmode, motionmodeState, motionmodeListgroupItemState, motionmodeListgroupItemtext, motionmodeListgroupItemDataState, 
        ani_speed, ListgroupItem_file_prefix, link_working, train_working, train_end, cancelmotioning } from '$lib/data';
    import { send_serial_emit, test } from '$lib/link'
    import { start_collection, end_collection, load_collection, delete_file } from '$lib/momodecom'
    import { cancelmotion } from '$lib/utils'

    import { Alert, Toggle, ButtonGroup, NumberInput, InputAddon, Button, Listgroup, ListgroupItem, Modal, Spinner, Input } from 'flowbite-svelte';
    import { AngleLeftOutline, AngleRightOutline, CloseOutline, InfoCircleSolid, PlusOutline } from 'flowbite-svelte-icons';
    import { fade, fly, draw, slide } from 'svelte/transition';


    let STM32Alert:boolean = $state(false);
    let STM32Alert_fail_Toggle:boolean = $state(false);
    let STM32Alert_fail_Alert:boolean = $state(false);

    const Trainingmode_paddingX = $derived($motionmode == "训练模式" ? 'px-8' : 'px-3');
    const Followmode_paddingX = $derived($motionmode == "跟随模式" ? 'px-8' : 'px-3');

    const Trainingmode_color = $derived($motionmode == "训练模式" ? 'green' : 'light');
    const Followmode_color = $derived($motionmode == "跟随模式" ? 'green' : 'light');

    let entering:boolean = $state(false);
    let entering_alert:boolean = $state(false);
    let entering_alert_timeout:boolean = $state(false);

    let entered_alert:boolean = $state(false);
    let entered_alert_timeout:boolean = $state(false);
    
    let formModal = $state(false);
    let Modal_select:string = $state("");
    let Modal_select_temp:number = 0; 

    function STM32Alert_fail() {
        if (STM32Alert_fail_Toggle == false){
            STM32Alert_fail_Toggle = true;
            setTimeout(() => {$STM32_Power = false;STM32Alert_fail_Toggle = false;},500);
        }

        if (STM32Alert_fail_Alert == false){
            STM32Alert = true;
            STM32Alert_fail_Alert = true
            setTimeout(() => {STM32Alert = false;STM32Alert_fail_Alert = false;},2000);
        }
    }

    function the_entering_alert() {
        entering_alert = true;
        if (!entering_alert_timeout){
            entering_alert_timeout = true;
            setTimeout(() => {entering_alert = false; entering_alert_timeout = false;},2000);
        }
    }

    function the_entered_alert() {
        entered_alert = true;
        if (!entering_alert_timeout){
            entering_alert_timeout = true;
            setTimeout(() => {entered_alert = false; entered_alert_timeout = false;},2000);
        }
    }
    
    function begin_cancelmotion() {
        $train_working = false;

        $cancelmotioning = true;
    }

</script>

{#if STM32Alert}
<div class="fixed" in:fly={{ x: 2000, duration: 500 }} out:fly={{ x: -200, duration: 200 }}>
    <Alert color="red">
        <div class="flex">
        <InfoCircleSolid />
        <span class="mx-2">设备无法连接</span>
        </div>
    </Alert>
</div>
{/if}

{#if entering_alert}
<div class="fixed" in:fly={{ x: 2000, duration: 500 }} out:fly={{ x: -200, duration: 200 }}>
    <Alert color="yellow">
        <div class="flex">
        <InfoCircleSolid />
        <span class="mx-2">录入中,请勿点击</span>
        </div>
    </Alert>
</div>
{/if}

{#if entered_alert}
<div class="fixed" in:fly={{ x: 2000, duration: 500 }} out:fly={{ x: -200, duration: 200 }}>
    <Alert color="green">
        <div class="flex">
        <InfoCircleSolid />
        <span class="mx-2">录入完毕</span>
        </div>
    </Alert>
</div>
{/if}

{#if $cancelmotioning}
<div class="fixed" in:fly={{ x: 2000, duration: 500 }} out:fly={{ x: -200, duration: 200 }}>
    <Alert color="yellow">
        <div class="flex">
        <InfoCircleSolid />
        <span class="mx-2">停止中(请等待本次训练完成)</span>
        </div>
    </Alert>
</div>
{/if}

{#if $train_end }
<div class="fixed" in:fly={{ x: 2000, duration: 500 }} out:fly={{ x: -200, duration: 200 }}>
    <Alert color="green">
        <div class="flex">
        <InfoCircleSolid />
        <span class="mx-2">本次训练结束</span>
        </div>
    </Alert>
</div>
{/if}

<Alert class="opacity-70 transition-shadow duration-300 ease-in-out hover:shadow-lg ">
    状态:
    {#if $Power}
    <Alert color="green">
        正在运行
    </Alert>
    {:else}
    <Alert color="red">
        设备以全部关闭
    </Alert>
    {/if}
    
    <div class="mt-[2rem]">设备总开关</div>
    <Toggle class="p-2" checked={$Power} onclick={() => Power.update(value => value = !value)}>
        
    </Toggle>
</Alert>

<div class="grid gap-4 place-items-start">
    <!-- 该<div>占位 -->
    <div></div>

    <!-- {#if $shebeiState }
    <div transition:slide class="w-full grid place-center">
        <ul in:fly={{ x: -600, duration: 500 }} out:fly={{ x: -200, duration: 200 }} class="w-[80%] m-auto bg-white rounded-lg border border-gray-200 dark:bg-gray-800 dark:border-gray-600 divide-y divide-gray-200 dark:divide-gray-600 transition-shadow duration-300 ease-in-out hover:shadow-lg ">
            <li class="p-4 text-center"><CloseOutline class="absolute m-0.9" onclick={() => {$shebeiState = !$shebeiState}}></CloseOutline><span>设备控制</span></li>
            <li class="p-3"><Toggle onclick={() => {STM32Alert_fail()}} bind:checked={$STM32_Power}>STM32{#if $STM32_Power}运行{:else}关闭{/if}</Toggle></li>
            <li class="p-3"><Toggle></Toggle></li>
            <li class="p-3"><Toggle></Toggle></li>
            <li class="p-3"><Toggle></Toggle></li>
        </ul>
    </div>
    {/if}

    {#if $jiankongState }
    <div transition:slide class="w-full grid place-center">
        <ul in:fly={{ x: -600, duration: 500 }} out:fly={{ x: -200, duration: 200 }} class="w-[80%] m-auto bg-white rounded-lg border border-gray-200 dark:bg-gray-800 dark:border-gray-600 divide-y divide-gray-200 dark:divide-gray-600 transition-shadow duration-300 ease-in-out hover:shadow-lg ">
            <li class="p-4 text-center"><CloseOutline class="absolute m-0.9" onclick={() => {$jiankongState = !$jiankongState}}></CloseOutline><span>监视台</span></li>
            <li class="p-3"><Toggle  bind:checked={$Stm32_chart}>STM32图表</Toggle></li>
            <li class="p-3"><Toggle  bind:checked={$Motor_1_chart}>电机1图表</Toggle></li>
            <li class="p-3"><Toggle  bind:checked={$Motor_2_chart}>电机2图表</Toggle></li>
            <li class="p-3"><Toggle  bind:checked={$V_I_chart}>电压电流图表</Toggle></li>
        </ul>
    </div>
    {/if} -->

    {#if JSON.stringify($motionmodeListgroupItemState) != JSON.stringify([false, false, false, false])}
    <div transition:fade class="absolute translate-x-[17rem] translate-y-[-3rem]">
        <Button disabled={$train_working || $cancelmotioning} color='red'class="py-2 px-3" onclick={() => {
            if ($train_working) {
                //运行时期删除是容易误触的，还是禁用的好
            }else{
                delete_file($ListgroupItem_file_prefix);

                $motionmodeListgroupItemState = [false, false, false, false];
                $motionmodeListgroupItemtext[$ListgroupItem_file_prefix] = "";
                $motionmodeListgroupItemDataState[$ListgroupItem_file_prefix] = false;
            };
            }}>
            <span>删除</span>
        </Button>
    </div>
        <!-- {#if  } -->
        <div transition:slide class="mx-auto my-1">
            {#if $train_working}
            <ButtonGroup>
                <Button disabled color="green">
                    <Spinner class="me-3" size="4" color="white" />
                    训练中
                </Button>
                <Button color="yellow" onclick={() => {begin_cancelmotion();}}>
                    停止
                </Button>
            </ButtonGroup>
            {:else}
            <Button disabled={$train_working || $cancelmotioning} color='primary' class="py-2 px-3" on:click={() => {
                $train_working = true;
                load_collection($ListgroupItem_file_prefix + "_" + $motionmodeListgroupItemtext[$ListgroupItem_file_prefix]);
                }}>
                <span>运行</span>
            </Button>
            <Button color='yellow' class="py-2 px-3" on:click={() => {
                begin_cancelmotion();
                }}>
                <span>取消</span>
            </Button>
            {/if}
        </div>
        <!-- {/if} -->
    {/if}
    <div class="w-full p-4 grid place-center rounded-lg bg-sky-100">
        <div class="w-[80%] grid place-center m-auto">
                <ButtonGroup class="p-3 m-auto">
                    <Button disabled = {!$link_working || $cancelmotioning} class="{Trainingmode_paddingX} py-3 opacity-90" 
                    color={Trainingmode_color} 
                    onclick={() => {
                        if($motionmode == "" || $motionmode == "跟随模式"){
                            $motionmode = "训练模式";
                            send_serial_emit("g");
                        }else{
                            $motionmode = ""};
                        }}>训练模式</Button>
                    <Button disabled = {!$link_working || $cancelmotioning} class="{Followmode_paddingX} py-3 opacity-90" 
                    color={Followmode_color} 
                    onclick={() => {
                        if($motionmode == "" || $motionmode == "训练模式"){
                            $motionmode = "跟随模式";
                            send_serial_emit("h");

                            if ($train_working) {
                                begin_cancelmotion();
                            }else{
                                $motionmodeListgroupItemState = [false, false, false, false];
                            };

                        }else{
                            $motionmode = ""};
                        }}>跟随模式</Button>
                </ButtonGroup>
        </div>


        {#if $motionmodeState && $motionmode == "训练模式" }
        <div in:fly={{ x: -600, duration: 500 }} out:fly={{ x: -200, duration: 200 }} class="w-[85%] grid place-center m-auto">
            <!-- <ul in:fly={{ x: -600, duration: 500 }} out:fly={{ x: -200, duration: 200 }} class="w-[80%] m-auto bg-white rounded-lg border border-gray-200 dark:bg-gray-800 dark:border-gray-600 divide-y divide-gray-200 dark:divide-gray-600 transition-shadow duration-300 ease-in-out hover:shadow-lg ">
                <li class="p-4 text-center"><CloseOutline class="absolute m-0.9" onclick={() => {$motionmodeState = !$motionmodeState}}></CloseOutline><span>运动模式选择</span></li>
                <li class="p-3"><Button color="alternative" bind:checked={$Stm32_chart}>STM32图表</Button></li>
                <li class="p-3"><Button color="alternative" bind:checked={$Motor_1_chart}>电机1图表</Button></li>
                <li class="p-3"><Button color="alternative" bind:checked={$Motor_2_chart}>电机2图表</Button></li>
                <li class="p-3"><Button color="alternative" bind:checked={$V_I_chart}>电压电流图表</Button></li>
            </ul> -->
            <Listgroup active class="">
                <div class="p-4 text-center hover:shadow">
                    <CloseOutline class="absolute m-auto my-[2px]" onclick={() => {$motionmodeState = !$motionmodeState}} />
                    <span>动作选择</span>
                    <!-- <Button class="absolute mx-4 my-[1px] px-3 py-1" size="xs" color="green" pill outline>新建</Button> -->
                </div>
                <ListgroupItem disabled={$train_working || $cancelmotioning} current={$motionmodeListgroupItemState[0]} 
                    on:click={() => {$motionmodeListgroupItemState.fill(false);
                        if (!entering){
                            if($motionmodeListgroupItemtext[0] == "") {
                                formModal = true;
                                Modal_select_temp = 0;
                                
                            }else if(!$motionmodeListgroupItemDataState[0]){

                            }else{
                                if ($motionmodeListgroupItemState[0] == false){
                                    $motionmodeListgroupItemState[0] = true;
                                    $ListgroupItem_file_prefix = 0;
                                    
                                    $train_working = false;
                                }
                            }    
                        }else{
                            the_entering_alert();
                        }
                        // test();
                        }}>
                    <div class="m-auto">
                        {#if $motionmodeListgroupItemtext[0] != ""}
                        
                            {#if !$motionmodeListgroupItemDataState[0]}
                            <Button color="red" class="mx-1 px-10 z-100" onclick={() => {
                                entering = false;
                                the_entered_alert();
                                $motionmodeListgroupItemDataState[0] = true;
                                // setTimeout(() => {$motionmodeListgroupItemState[0] = false;},0);//不知道为什么这个值会变true，触发时load_collection()也没执行，所以这里选择置false。
                                end_collection();
                            }}>
                                <Spinner class="me-3" size="4" color="white" />
                                录入中
                            </Button>
                            {/if}
                        <span>{$motionmodeListgroupItemtext[0]}</span>

                        {:else}
                        <PlusOutline />
                        {/if}
                    </div>
                </ListgroupItem>
                <ListgroupItem disabled={$train_working || $cancelmotioning} current={$motionmodeListgroupItemState[1]} 
                    on:click={() => {$motionmodeListgroupItemState.fill(false);
                        if (!entering){
                            if($motionmodeListgroupItemtext[1] == "") {
                                formModal = true;
                                Modal_select_temp = 1;

                            }else if(!$motionmodeListgroupItemDataState[1]){

                            }else{
                                if ($motionmodeListgroupItemState[1] == false){
                                    $motionmodeListgroupItemState[1] = true;
                                    $ListgroupItem_file_prefix = 1;

                                    $train_working = false;
                                }
                            }   
                        }else{
                            the_entering_alert();
                        }
                        }}>
                    <div class="m-auto">
                        {#if $motionmodeListgroupItemtext[1] != ""}

                            {#if !$motionmodeListgroupItemDataState[1]}
                            <Button color="red" class="mx-1 px-10 z-100" onclick={() => {
                                entering = false;
                                the_entered_alert();
                                $motionmodeListgroupItemDataState[1] = true;
                                // setTimeout(() => {$motionmodeListgroupItemState[1] = false;},0);//不知道为什么这个值会变true，触发时load_collection()也没执行，所以这里选择置false。
                                end_collection();
                            }}>
                                <Spinner class="me-3" size="4" color="white" />
                                录入中
                            </Button>
                            {/if}
                        <span>{$motionmodeListgroupItemtext[1]}</span>

                        {:else}
                        <PlusOutline />
                        {/if}
                    </div>
                </ListgroupItem>
                <ListgroupItem disabled={$train_working || $cancelmotioning} current={$motionmodeListgroupItemState[2]} 
                    on:click={() => {$motionmodeListgroupItemState.fill(false);
                        if (!entering){
                            if($motionmodeListgroupItemtext[2] == "") {
                                formModal = true;
                                Modal_select_temp = 2;

                            }else if(!$motionmodeListgroupItemDataState[2]){

                            }else{
                                if ($motionmodeListgroupItemState[2] == false){
                                    $motionmodeListgroupItemState[2] = true;
                                    $ListgroupItem_file_prefix = 2;
                                    
                                    $train_working = false;
                                }
                            }   
                        }else{
                            the_entering_alert();
                        }
                        }}>
                    <div class="m-auto">
                        {#if $motionmodeListgroupItemtext[2] != ""}
                        
                            {#if !$motionmodeListgroupItemDataState[2]}
                            <Button color="red" class="mx-1 px-10 z-100" onclick={() => {
                                entering = false;
                                the_entered_alert();
                                $motionmodeListgroupItemDataState[2] = true;
                                // setTimeout(() => {$motionmodeListgroupItemState[2] = false;},0);//不知道为什么这个值会变true，触发时load_collection()也没执行，所以这里选择置false。
                                end_collection();
                            }}>
                                <Spinner class="me-3" size="4" color="white" />
                                录入中
                            </Button>
                            {/if}
                        <span>{$motionmodeListgroupItemtext[2]}</span>
                        {:else}
                        <PlusOutline />
                        {/if}
                    </div>
                </ListgroupItem>
                <ListgroupItem disabled={$train_working || $cancelmotioning} current={$motionmodeListgroupItemState[3]} 
                    on:click={() => {$motionmodeListgroupItemState.fill(false);
                        if (!entering){
                            if($motionmodeListgroupItemtext[3] == "") {
                                formModal = true;
                                Modal_select_temp = 3;

                            }else if(!$motionmodeListgroupItemDataState[3]){

                            }else{
                                if ($motionmodeListgroupItemState[3] == false){
                                    $motionmodeListgroupItemState[3] = true;
                                    $ListgroupItem_file_prefix = 3;
                                    
                                    $train_working = false;
                                }
                            }   
                        }else{
                            the_entering_alert();
                        }  
                        }}>
                    <div class="m-auto">
                        {#if $motionmodeListgroupItemtext[3] != ""}
        
                            {#if !$motionmodeListgroupItemDataState[3]}
                            <Button color="red" class="mx-1 px-10 z-100" onclick={() => {
                                entering = false;
                                the_entered_alert();
                                $motionmodeListgroupItemDataState[3] = true;
                                // setTimeout(() => {$motionmodeListgroupItemState[3] = false;},0);//不知道为什么这个值会变true，触发时load_collection()也没执行，所以这里选择置false。
                                end_collection();
                            }}>
                                <Spinner class="me-3" size="4" color="white" />
                                录入中
                            </Button>
                            {/if}
                        <span>{$motionmodeListgroupItemtext[3]}</span>
                        {:else}
                        <PlusOutline />
                        {/if}
                    </div>
                </ListgroupItem>
                <div class="p-3 flex justify-between hover:shadow">
                    <AngleLeftOutline class="mx-5" />
                    <AngleRightOutline class="mx-6" />
                </div>
            </Listgroup>
        </div>
        {:else if $motionmode == "跟随模式" }
        <div class="w-[70%] m-auto">
            <Button disabled class="w-[100%]">
                <Spinner class="me-3" size="4" color="white" />
                手臂跟随中
            </Button>
        </div>
        {:else if $motionmode == "" && $link_working }
        <div class="w-[70%] m-auto">
            <Alert border color="blue">
                <InfoCircleSolid slot="icon" class="w-5 h-5" />
                请选择模式
            </Alert>
        </div>
        {:else if !$link_working }
        <div class="w-[70%] m-auto">
            <Alert border color="red">
                <InfoCircleSolid slot="icon" class="w-5 h-5" />
                请进入设置通信
            </Alert>
        </div>
        {/if}
    </div>

    <!-- <div transition:slide class="w-full grid place-center">
        <div class="w-[80%] m-auto dark:border-gray-600 divide-y divide-gray-200 dark:divide-gray-600 transition-shadow duration-300 ease-in-out ">
            <div>
                动画速度
                <ButtonGroup>
                    <NumberInput type="text" id="Baud_rate" bind:value={$ani_speed} />
                    <InputAddon>ms</InputAddon>
                </ButtonGroup>
            </div>
        </div>
    </div> -->
</div>

<Modal bind:open={formModal} size="xs" autoclose={false} class="w-full">
    <form class="flex flex-col space-y-6" action="#">
        <h3 class="mb-4 text-xl font-medium text-gray-900 dark:text-white mx-auto">录入名称选择</h3>
        <pre class="mx-auto">{Modal_select}</pre>

        <Input type="text" autofocus bind:value={Modal_select} />
        <!-- <ButtonGroup class="space-x-px mx-auto" onclick = {() => {}}>
            <Button pill color="red" onclick = {() => {Modal_select = "肩部前屈";}}>肩部前屈</Button>
            <Button pill color="green" onclick = {() => {Modal_select = "肘部屈曲";}}>肘部屈曲</Button>
            <Button pill color="yellow" onclick = {() => {Modal_select = "肘部伸展";}}>肘部伸展</Button>
            <Button pill color="purple" onclick = {() => {Modal_select = "端碗动作";}}>端碗动作</Button>
        </ButtonGroup> -->
        {#if Modal_select!=""}
        <div transition:slide class="w-[40%] mx-auto">
            <Button class="w-[100%]" onclick={() => {
                if (Modal_select_temp == 0) {
                    $motionmodeListgroupItemtext[0] = Modal_select;
                } else if (Modal_select_temp == 1) {
                    $motionmodeListgroupItemtext[1] = Modal_select;
                } else if (Modal_select_temp == 2) {
                    $motionmodeListgroupItemtext[2] = Modal_select;
                } else if (Modal_select_temp == 3) {
                    $motionmodeListgroupItemtext[3] = Modal_select;
                }

                start_collection( String(Modal_select_temp) +"_" + $motionmodeListgroupItemtext[Modal_select_temp] );

                entering = true;
                formModal = false;
                Modal_select = "";
                }}>记录</Button>
        </div>
        {/if}
    </form>
</Modal>